package com.boyicloud.exchangeserver.common

import io.jsonwebtoken.CompressionCodecs
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.SignatureAlgorithm
import kotlin.Throws
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.stereotype.Component
import java.lang.Exception
import java.util.*

/**
 * @author lengchunyun
 */
@Component
class TokenManager {

    private val tokenExpiration = (24 * 60 * 60 * 1000).toLong()
    private val tokenSignKey = "4346"

    fun createToken(username: String?): String {
        return Jwts.builder().setSubject(username)
            .setExpiration(Date(System.currentTimeMillis() + tokenExpiration))
            .signWith(SignatureAlgorithm.HS512, tokenSignKey).compressWith(CompressionCodecs.GZIP).compact()
    }

    @Throws(BadCredentialsException::class)
    fun getUserFromToken(token: String?): String {
        val username: String = try {
            Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).body.subject
        } catch (e: Exception) {
            throw BadCredentialsException(e.message)
        }
        return username
    }

    fun removeToken(token: String?) {}
}